<?php

namespace app\product\logic;
use app\common\library\Excel;
use app\product\logic\BasicLogic;
use app\product\model\ProductModel;
use app\product\model\ProductSellerSkuModel;
use app\product\model\ProductMonthCostModel;
use think\facade\Db;
use think\facade\Config;
class ProductLogic extends BasicLogic
{
    //注入所需模型以及操作类
    protected $productModel          = null;
    protected $productSellerSkuModel = null;
    protected $productMonthCostModel  = null;
    public function __construct(
        ProductModel          $productModel,
        ProductSellerSkuModel $productSellerSkuModel,
        ProductMonthCostModel $productMonthCostModel,
    )
    {
        $this->productModel            = $productModel;
        $this->productSellerSkuModel   = $productSellerSkuModel;
        $this->productMonthCostModel   = $productMonthCostModel;
    }

    /**
     * @desc  产品列表
     * @date  2024/4/20
     */
    public function getProductList($params=[]){
        $limit           = getIsset($params,'limit',10);
        $sku             = getIsset($params,'sku');
        $product_id      = getIsset($params,'product_id');
        $where = [];
        if($sku){
            $where[] = ['sku', 'like', '%' . $sku . '%'];
        }

        if($product_id){
            $where[] = ['product_id', 'like', '%' . $product_id . '%'];
        }
        $res = $this->productModel->where($where)->order('created_time desc')->paginate($limit);;
        $data = [
            'list'   => $res->items()?:[],
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc  获取详情
     * @date  2024/4/20
     */
    public function getInfo($params=[]){
        $product_id  = getIsset($params,'product_id');
        $limit       = getIsset($params,'limit',10);
        $page        = getIsset($params,'page',1);
        if(!$product_id){
            return  $this->jsonMessage(201,false,'产品ID不能为空!',null);
        }



       $list = $this->productSellerSkuModel
            ->where('product_id',$product_id)
            ->limit(($page - 1) * $limit, $limit)
            ->select();
       $list  = objectToArray($list);
       $count = $this->productSellerSkuModel
           ->where('product_id',$product_id)
           ->count();
        $data = ['list'=>$list,'total'=>$count];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }

    /**
     * @desc  产品订单预估值计算
     * @date  2024/4/20
     * @author  luckyXiong
     */
    public function getProductEditList($params=[]){
        $limit           = getIsset($params,'limit',10);
        $sku             = getIsset($params,'sku');
        $product_id      = getIsset($params,'product_id');
        $where = [];
        if($sku){
            $where[] = ['sku', 'like', '%' . $sku . '%'];
        }

        if($product_id){
            $where[] = ['product_id', 'like', '%' . $product_id . '%'];
        }
        $res = $this->productModel->where($where)->order('created_time desc')->paginate($limit);;
        $data = [
            'list'   => $res->items()?:[],
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }

    /**
     * @desc    产品订单预估值计算编辑单条记录
     * @date    2024/4/20
     * @author  luckyXiong
     */
    public function get_row($id=''){
        $field = [
            'p.id','p.product_name','p.product_id','p.sku','p.created_time','e.created_time',
             'e.num_1','e.num_2','e.num_3','e.num_4','e.num_above_5','e.refund_rate',
        ];
           $info = Db::name('product')->alias('p')
               ->leftJoin('ba_product_order_estimate e', 'e.product_id = p.product_id')
               ->field($field)
               ->where('p.id',$id)
               ->find();
       return  $info;
    }


    /**
     * @desc    财务订单值预估
     * @date    2024/4/20 getProductFeeList
     * @author  luckyXiong
     */
    public function editOrderFinancial($data=[]){
        $product_id = getIsset($data,'product_id');
        $exist_info = Db::name('product_order_estimate')->where('product_id',$product_id)->find();
        if(!$exist_info){
            $insert= [
                'product_id'  =>$product_id,
                'num_1'       =>$data['num_1']??'',
                'num_2'       =>$data['num_2']??'',
                'num_3'       =>$data['num_3']??'',
                'num_4'       =>$data['num_4']??'',
                'num_above_5' =>$data['num_above_5']??'',
                'refund_rate' =>$data['refund_rate']??'',
                'created_time'=>date("Y-m-d H:i:s", time()),
            ];
            Db::name('product_order_estimate')->insert($insert);
        }else{
            Db::name('product_order_estimate')->where('product_id',$product_id)->update([
                    'num_1'      =>$data['num_1']??'',
                    'num_2'      =>$data['num_2']??'',
                    'num_3'      =>$data['num_3']??'',
                    'num_4'      =>$data['num_4']??'',
                    'num_above_5'=>$data['num_above_5']??'',
                    'refund_rate'=>$data['refund_rate']??'',
                ]
            );
        }
        return  $this->jsonMessage(200,true,'操作成功',null);
    }




    /**
     * @desc    财务订单值预估
     * @date    2024/4/24
     * @author  luckyXiong
     */
    public function getProductFeeList($params){
        $sku             = getIsset($params,'sku');
        $date            = getIsset($params,'date');
        $limit           = getIsset($params,'limit',10);
        $where = [];

        if($sku){
            $where[] = ['sku', 'like', '%' . $sku . '%'];
        }

        if($date){
            $where[] = ['date', '=', $date];
        }
        $res =$this->productMonthCostModel->where($where)->order('operate_time desc')->paginate($limit);;

        $data = [
            'list'   => $res->items()?:[],
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }



    /**
     * @desc    导出下载模版
     * @date    2024/4/24
     * @author  luckyXiong
     */
    public function getExportInfo($params){
        $date  = getIsset($params,'date');
        $list  = Config('Logisticskey.current_spu');
        $arr   = [];
        foreach($list as $v){
            $arr[] = [
                'date'=>$date,
                'sku' =>$v,
                'cost'=>'',
            ];
        }
        $header[] = ['月份', 'date'];
        $header[] = ['商品名','sku'];
        $header[] = ['采购成本','cost'];
        $fileName = "month_spu_export_".$date;
        return Excel::exportData($arr, $header, $fileName, 'xlsx');
    }




    /**
     * @desc    编辑数据
     * @date    2024/4/24
     * @author  luckyXiong
     */
    public function updateCost($params=[]){
        $id   = getIsset($params,'id');
        $cost = getIsset($params,'cost');
        $res = Db::name('product_month_cost')->where('id',$id)->update(['cost'=>$cost,'operate_time'=>date("Y-m-d H:i:s", time())]);
        return  $this->jsonMessage(200,true,'操作成功',$res);
    }



    /**
     * @desc    上传数据
     * @date    2024/4/24
     * @author  luckyXiong
     */
    public function getUploadInfo($url){
        $data         = Excel::getExcelData('.' . '/' . $url);
        $excelData    = isset($data[0]) ? $data[0] : $data;
        if(!$excelData)  return json(DefaultResponse(201, false, '暂无数据!', null));
        $excelData    = filterArr($excelData);
        foreach ($excelData as $value) {
           $date = isset($value['A'])&& $value['A'] ? str_replace("\t", "", $value['A']):'';
           $sku  = isset($value['B'])&& $value['B'] ? str_replace("\t", "", $value['B']):'';
           $cost = isset($value['C'])&& $value['C'] ? str_replace("\t", "", $value['C']):'';
           $exist_info = Db::name('product_month_cost')->where(['date'=>$date,'sku'=>$sku])->find();
           if($exist_info){
               $arr_update  = [
                   'date'           => $date,
                   'sku'            => $sku,
                   'cost'           => $cost,
                   'operate_time'   => date("Y-m-d H:i:s", time()),
               ];
               Db::name('product_month_cost')->where('id',$exist_info['id'])->update($arr_update);
           }else{
               $arr_insert = [
                   'date'           => isset($value['A'])&& $value['A'] ? str_replace("\t", "", $value['A']):'',
                   'sku'            => isset($value['B'])&& $value['B'] ? str_replace("\t", "", $value['B']):'',
                   'cost'           => isset($value['C'])&& $value['C'] ? str_replace("\t", "", $value['C']):'',
                   'operate_time'   => date("Y-m-d H:i:s", time()),
               ];
               Db::name('product_month_cost')->insert($arr_insert);
           }
        }
        return  '导入成功';
    }


    /**
     * @desc  获取产品售卖列表
     * @date  2024-04-25
     * @author  luckyXiong
     */
    public function getSpuInfo(){
        $list  = Config('Logisticskey.current_spu');
        return  $this->jsonMessage(200,true,'获取成功',$list);
    }



    /**
     * @desc  获取产品售卖统计列表
     * @date  2024-04-25
     * @author  luckyXiong
     */
    public function getProductNumList($params=[]){
        $shop_id         = getIsset($params,'shop_id');
        $date            = getIsset($params,'date');
        $limit           = getIsset($params,'limit',10);
        $where = [];
        if($shop_id){
            $where[] = ['shop_id', '=', $shop_id];
        }

        if($date){
            $where[] = ['date', '=', $date];
        }
        $res = Db::name('product_month_spu')->where($where)
               ->order('operate_time desc')
               ->paginate($limit);
        $list = $res->items()?:[];
        $list = self::change_data($list);
        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }



    /**
     * @desc  获取产品售卖统计列表
     * @date  2024-04-25
     * @author  luckyXiong
     */
    public function exportInfo($params=[]){
        $shop_id         = getIsset($params,'shop_id');
        $date            = getIsset($params,'date');
        $where = [];
        if($shop_id){
            $where[] = ['shop_id', '=', $shop_id];
        }

        if($date){
            $where[] = ['date', '=', $date];
        }
        $list = Db::name('product_month_spu')->where($where)
            ->order('operate_time desc')
            ->select()->toArray();
        $list = self::change_data($list);

        $header[] = ['店铺', 'shop_name'];
        $header[] = ['月份', 'date'];
        $header[] = ['bra10', 'bra10'];
        $header[] = ['bra81', 'bra81'];
        $header[] = ['bra86', 'bra86'];
        $header[] = ['sha01', 'sha01'];
        $header[] = ['sha02', 'sha02'];
        $header[] = ['sha08', 'sha08'];
        $header[] = ['sha14', 'sha14'];
        $header[] = ['sha21', 'sha21'];
        $header[] = ['sha41', 'sha41'];
        $header[] = ['sha43', 'sha43'];
        $header[] = ['sha66', 'sha66'];
        $header[] = ['总件数', 'month_sum'];
        $fileName = "export_spu_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }








   /**
    * @desc展示数据处理
    * @author xx
    */
   public function change_data($list){
       $info  = Config('Logisticskey.current_spu');
       $data  = [];
       //批量获取店铺信息及sku数量信息;
       $shop_ids      = array_column($list,'shop_id');
       $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select();
       $shopInfos     = objectToArray($shopInfos);
       $shopInfos_map = array_column($shopInfos,null,'id');
       foreach($list as $k=>$v){
           $shop_names = $shopInfos_map[$v['shop_id']]??[];
           $data[$k]['id']           = $v['id'];
           $data[$k]['shop_id']      = $v['shop_id'];
           $data[$k]['shop_name']    =  $shop_names['name']??'';
           $data[$k]['date']         = $v['date'];
           $data[$k]['month_sum']    = $v['month_sum'];
           $data[$k]['operate_time'] = $v['operate_time'];
           $json_info                = json_decode($v['json'],true);
           $json_info_map            = array_column($json_info,null,'spu');
           foreach($info as $value){
               $spu_info = $json_info_map[$value]??[];
               $data[$k][$value] = $spu_info['total']??'0';
           }
       }
      return $data;
   }














}